﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;

using System.Web.UI.WebControls;
using Model;
using Resources;
using Service;

public partial class Models : System.Web.UI.Page
{

    readonly ReferenceDataService _ReferenceDataService = new ReferenceDataService();
    readonly StockService _StockService = new StockService();
    EquipmentSystem _system = new EquipmentSystem();
    private DirectService _DirectService = new DirectService();

    protected void Page_Load(object sender, EventArgs e)
    {
      


   //   lblTotalModel.Text = "Total model:" + _ReferenceDataService.GetModels().Count;

      //  txtHiddenSystemId.Text = Request.QueryString["systemsId"];
        if (Session["whereClause"] == null)
            Session["whereClause"] = txtHiddenWhereClause.Text;
        if (Session["orderByClause"] == null)
            Session["orderByClause"] = txthiddenOrderbyClause.Text;

        new Utility().SetRowToDisplay(grdModel, Session["rowsToSDisplay"]);
        if (!IsPostBack)
        {
            // to avoid loading for the first time


            if (Session["pageIndex"] != null)
            {
                grdModel.PageIndex = Int32.Parse(Session["pageIndex"].ToString());

            }



            /* 
             * 1. number of equipments
             * 2. select the element 
             * */
            

        }
        else
        {
            txtHiddenPageIndex.Text = "0";
            //  SystemList = new DirectService().DataTableToIlistSystem(GetWhereClause(), GetOrderClause());
             lblTotalModel.Text = "Total model : " + new DirectService().GetModelDisplayed(GetWhereClause(), GetOrderClause()).Rows.Count;
            int number = +new DirectService().GetModelDisplayed(GetWhereClause(), GetOrderClause()).Rows.Count;
            if (number == 0)
            {
                grdModel1.Visible = true;
            }
            else
            {
                grdModel.Visible = true; 
                grdModel1.Visible = false;
            }
        }

        grdModel.PageIndex = !String.IsNullOrEmpty(txtHiddenPageIndex.Text) ? Int32.Parse(txtHiddenPageIndex.Text) : 0;

    }

    protected string GetWhereClause()
    {
        string whereClause = string.Empty;
        string and = "";
        string str = "";

        // Prepare by equipement
        int i = 0;
        if (!string.IsNullOrEmpty(txtModelId.Text))
        {
            if(int.TryParse(txtModelId.Text,out i))
            {
                and = " and ";
                str = " where Model.ModelId=" + Int32.Parse(txtModelId.Text);
                if (txtModelLabel.Text != string.Empty)
                {
                    str += " " + "and" + " " + "Model.Model=" + "'" + txtModelLabel.Text + "'";
                    and = " and ";
                }
            }
            else
            {
                grdModel.Visible = false;
                grdModel1.Visible = true;
                lblTotalModel.Text = "Total model : 0";
                return null;
            }
        }
        else
        {
            if (txtModelLabel.Text != string.Empty)
            {
                str += " " + "where" + " " + "Model.Model like" + "'%" + txtModelLabel.Text + "%'";
                and = " and ";
            }
        }

        if (!String.IsNullOrEmpty(str))
            whereClause = str + " ";
        return whereClause;
    }
    protected string GetOrderClause()
    {
        return " Order by Model.Model";
    }

    public int GetTabIndex()
    {
        int tabIndex = Request.QueryString["tabIndex"] != null
                        ?
                            Int32.Parse(Request.QueryString["tabIndex"])
                        : 0;
        if (Session["defaultTabIndex"] != null)
        {
            tabIndex = Int32.Parse(Session["defaultTabIndex"].ToString());
            Session["defaultTabIndex"] = null;
        }

        return tabIndex;
    }

    public int GetPageIndex()
    {
        return Session["pageIndex"] != null
                   ?
                       Int32.Parse(Session["pageIndex"].ToString())
                   : 0;
    }

    protected void bntFilter_Click(object sender, EventArgs e)
    {
        Session["whereClause"] = GetWhereClause();
        Session["orderByClause"] = GetOrderClause();
        txthiddenOrderbyClause.Text = GetOrderClause();
        txtHiddenWhereClause.Text = GetWhereClause();
        Session["defaultTabIndex"] = 0;
        ClearControlSearch();
    }
    private void ClearControlSearch()
    {
        txtModelId.Text = "";
        txtModelLabel.Text = "";
        
    }
    protected void grdEquipment_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdModel.PageIndex = e.NewPageIndex;
        txtHiddenPageIndex.Text = grdModel.PageIndex.ToString();
        Session["pageIndex"] = grdModel.PageIndex;

    }
    protected void grdEquipment_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        grdModel.EditIndex = -1;
    }
    protected void grdSystem_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Delete"))
        {
            int authorId = Convert.ToInt32(grdModel.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
            _StockService.DeleteModel(authorId);
            Response.Redirect("Models.aspx");
        }

        new Utility().SetSelectedColorToGridView(e, grdModel);
    }
    protected void grdSystem_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        EquipmentModel _model = new EquipmentModel();

        if (e.Cancel == false)
        {
            bool flag = true;
            if (flag == false)
            {
                GridViewRow row = grdModel.Rows[e.RowIndex];
                _model.ModelId = Int32.Parse(row.Cells[2].Text);
                _model.ModelLabel = row.Cells[3].Text;
            }
        }

    }
    protected void grdSystem_RowEditing(object sender, GridViewEditEventArgs e)
    {

    }
    protected void grdSystem_RowUpdated(object sender, GridViewUpdatedEventArgs e)
    {

      //  Response.Redirect("Models.aspx");

    }
    protected void grdSystem_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {

    }
    protected void grdEquipment_RowDataBound1(object sender, GridViewRowEventArgs e)
    {

        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //block to add message
            string stringComplete = "";
            if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
            {
                LinkButton deleteButton = (LinkButton)e.Row.Cells[1].Controls[0];
                deleteButton.Attributes.Add("onclick", "return confirm('" + Resource.ConfirmDeleteMessage+ "?');");
            }
        }
    }
    protected void grdEquipment_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void grdSystem_Sorted(object sender, EventArgs e)
    {
        grdModel.DataBind();


    }
    protected void grdSystem1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        AddModel();
    }
    private void AddModel()
    {
        IList list = new ArrayList();
        list = _StockService.GetDepartment();

        for (int i = 0; i < list.Count; i++)
        {
            if (((Model.Department)list[i]).DepartmentLabel == txtModel.Text)
            {
                lblMessage.Visible = true;
                lblMessageValidate.Text = ""; 
                return;
            }
            lblMessage.Visible = false;
        }
        if (txtModel.Text != string.Empty)
        {
            EquipmentModel _model = new EquipmentModel();
            _model.ModelId = 0;
            _model.ModelLabel = txtModel.Text;
            _ReferenceDataService.SaveModel(_model);
            Session["defaultTabIndex"] = 0;
            grdModel1.Visible = false;
            lblTotalModel.Text = "Total model:" + _ReferenceDataService.GetModels().Count;
            ClearControlAdd();
            lblMessageValidate.Text = Resource.MessageValidate; 
            
        }
        
    }
    private void ClearControlAdd()
    {
        txtModel.Text = "";
    }
    protected string GetWhereClauseDemo()
    {
        return " where Model.Model=" + "'" + txtModel.Text + "'";
    }
    protected void dsModel_Selected(object sender, ObjectDataSourceStatusEventArgs e)
    {
        if (e.ReturnValue != null) lblTotalModel.Text = "Total model:" + ((DataTable)e.ReturnValue).Rows.Count;
    }
}
